import BaseInput from "@/components/base/Input"
import styled from "@emotion/styled"
import {
    CSSProperties,
    KeyboardEvent,
    RefObject,
    memo,
    useEffect,
    useImperativeHandle,
    useRef,
    useState,
} from "react"

type Props = {
    callBackSubmit?: (code: string) => void
    ref?: RefObject<unknown>
    onChangeCode?: (code: string) => void
    style?: CSSProperties
    className?: string
    autoSubmit?: boolean
}

const VerificationCodeInput = memo(
    ({ callBackSubmit, ref, onChangeCode, style, className = "", autoSubmit }: Props) => {
        const [codes, setCodes] = useState(Array(6).fill(""))
        const inputs = useRef(Array(6).fill(null))

        // 输入验证码后自动提交
        useEffect(() => {
            console.log("autoSubmit", autoSubmit)
            if (autoSubmit && codes.every((code) => code !== "")) {
                handleSubmit()
            }
            if (onChangeCode) {
                const code: string = codes.join("")
                onChangeCode(code)
            }
            // eslint-disable-next-line react-hooks/exhaustive-deps
        }, [codes])

        // 兄弟组件（倒计时组件）重新发送验证后初始化input
        useImperativeHandle(ref, () => ({
            resetInputs: () => {
                setCodes(Array(6).fill(""))
                inputs.current[0]?.focus()
            },
        }))

        const handleChange = (index: number, value: string) => {
            if (/^[0-9]$/.test(value)) {
                // 只允许数字
                const newCodes = [...codes]
                newCodes[index] = value
                setCodes(newCodes)

                // 自动聚焦下一个输入框
                if (index < 5 && value !== "") {
                    // inputs.current[index + 1].focus()
                    setTimeout(() => {
                        inputs.current[index + 1]?.focus()
                    }, 0)
                }
            }
        }
        //键盘删除input值
        const handleKeyDown = (index: number, e: KeyboardEvent<HTMLInputElement>) => {
            if (e.key === "Backspace" || e.key === "Delete") {
                e.preventDefault()
                const newCodes = [...codes]

                // 当前输入框有内容时：清空内容
                // 当前输入框无内容时：删除前一个内容
                if (codes[index] !== "") {
                    newCodes[index] = ""
                } else if (index > 0) {
                    newCodes[index - 1] = ""
                }

                setCodes(newCodes)

                // 焦点处理逻辑
                if (index > 0) {
                    const targetIndex = codes[index] !== "" ? index : index - 1
                    inputs.current[targetIndex].focus()
                }
            }
        }
        //粘贴验证码
        const handlePaste = (e: {
            preventDefault: () => void
            clipboardData: { getData: (arg0: string) => string | never[] }
        }) => {
            e.preventDefault()
            const pasteData = e.clipboardData.getData("text/plain").slice(0, 6)
            const newCodes = [...codes]
            if (typeof pasteData === "string") {
                pasteData.split("").forEach((char, i) => {
                    if (i < 6 && /^[0-9]$/.test(char)) {
                        newCodes[i] = char
                    }
                })
            }
            setCodes(newCodes)
        }

        const handleSubmit = () => {
            // 这里执行父组件提交逻辑
            if (callBackSubmit) {
                const code: string = codes.join("")
                callBackSubmit(code)
            }
        }
        const hasFocusedRef = useRef(false)
        return (
            <CodeInputBox
                onPaste={handlePaste}
                className={className}
            >
                {codes.map((code, index) => (
                    <CodeInput
                        style={style}
                        key={index}
                        type="text"
                        // max-length="1" //react写法
                        maxLength={1} //preact写法
                        value={code}
                        // @ts-ignore
                        // ref={(el: RefObject<unknown>) => (inputs.current[index] = el)}
                        ref={(el) => {
                            inputs.current[index] = el
                            if (index === 0 && el && !hasFocusedRef.current) {
                                ;(el as HTMLInputElement).focus() // 手动 focus 第一个 input
                                hasFocusedRef.current = true
                            }
                        }}
                        onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                            handleChange(index, e.target.value)
                        }
                        onKeyDown={(e: KeyboardEvent<HTMLInputElement>) => handleKeyDown(index, e)}
                        autoFocus={index === 0}
                    />
                ))}
            </CodeInputBox>
        )
    },
)

const CodeInputBox = styled.div`
    display: flex;
    justify-content: space-between;
`

const CodeInput = styled(BaseInput)`
    padding: 0;
    margin: 0;
    width: 48rem;
    height: 48rem;
    outline: none;
    border: 1rem solid #f2f3f5;
    border-radius: 8rem;
    background-color: #f2f3f5;
    font-family: "Gilroy";
    font-weight: 500;
    font-size: 32rem;
    line-height: 32rem;
    letter-spacing: 0;
    text-align: center;
    color: #0f0f10;

    &:focus {
        outline: 2rem solid #1e71ff;
        border-color: transparent;
        background-color: #fff;
    }
`

export default VerificationCodeInput
